// Tencent is pleased to support the open source community by making
// 蓝鲸智云 - 监控平台/日志平台 (BlueKing - Monitor/Log) available.
// Copyright (C) 2017-2022 THL A29 Limited, a Tencent company. All rights reserved.
// Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://opensource.org/licenses/MIT
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//

package servicediscoverer

import (
	"regexp"

	"go.opentelemetry.io/collector/model/pdata"
)

func NewMatcher() Matcher {
	return Matcher{}
}

type Matcher struct{}

func (Matcher) Match(span pdata.Span, re *regexp.Regexp, val string, groups map[string]string) bool {
	if re == nil {
		return false
	}

	match := re.FindStringSubmatch(val)
	mappings := make(map[string]string)
	for i, name := range re.SubexpNames() {
		if i != 0 && name != "" && len(match) > i {
			mappings[name] = match[i]
		}
	}
	if len(mappings) <= 0 {
		return false
	}

	for k, v := range mappings {
		if gk, ok := groups[k]; ok {
			k = gk
		}
		switch k {
		case "span_name":
			// span_name 直接覆盖
			span.SetName(v)
		default:
			// 其余 attributes 以数据本身优先 如若数据中不存在该 Key 则覆盖
			if _, ok := span.Attributes().Get(k); !ok {
				span.Attributes().UpsertString(k, v)
			}
		}
	}
	return true
}
